package com.shopper.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shopper.manager.config.ConfigCode;
import com.shopper.manager.config.RequestCode;
import com.shopper.manager.config.RequestMassage;
import com.shopper.manager.mapper.CustomerMapper;
import com.shopper.manager.model.customer.req.AddOrderReq;
import com.shopper.manager.model.customer.req.CustomerInfoReq;
import com.shopper.manager.model.customer.req.OrderGoodsReq;
import com.shopper.manager.model.customer.req.RegisteredReq;
import com.shopper.manager.model.customer.result.LoginResultBean;
import com.shopper.manager.model.index.UserBean;
import com.shopper.manager.model.order.NormsIds;
import com.shopper.manager.model.order.OrderCategoryBean;
import com.shopper.manager.model.order.req.GoodsListReq;
import com.shopper.manager.model.order.req.GoodsNormsAttributeReq;
import com.shopper.manager.model.order.req.NormsAttributeInsertReq;
import com.shopper.manager.model.order.req.NormsReq;
import com.shopper.manager.model.order.result.GoodsResultBean;
import com.shopper.manager.model.order.result.NormsBean;
import com.shopper.manager.model.order.result.OrderCategoryGoodsBean;
import com.shopper.manager.model.order.result.OrderIdResultBean;
import com.shopper.manager.service.TokenService;
import com.shopper.manager.until.MdProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class CustomerController extends BaseController {
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private TokenService tokenService;



    /**
     * 用户注册
     * @param bean
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("s1/customer/registered")
    public String registered(@RequestBody RegisteredReq bean) throws JsonProcessingException {
        if (bean != null) {
            String pwd = MdProcess.md5(bean.getCustomerPwd());
            bean.setCustomerPwd(pwd);
            RegisteredReq registeredState = customerMapper.selectAccount(bean);
            if (registeredState == null) {

                customerMapper.registerCustomer(bean);
                String token=tokenService.getCustomerToken(bean);
                bean.setToken(token);
                RegisteredReq registeredReq = customerMapper.selectAccount(bean);
                CustomerInfoReq customerInfoReq=new CustomerInfoReq();
                customerInfoReq.setAge("18");
                customerInfoReq.setName("小兔兔");
                customerInfoReq.setHeaderImage("");
                customerInfoReq.setBusinessLicense(registeredReq.getBusinessLicense());
                customerInfoReq.setUserId(registeredReq.getId());
                customerInfoReq.setLevel(1);
                customerInfoReq.setSex("-1");
                customerInfoReq.setToken(token);
                customerInfoReq.setPhone(registeredReq.getCustomerAccount());
                customerMapper.insertCustomerInfo(customerInfoReq);

                return getsBaseBean(RequestCode.SUCCESS_CODE, RequestMassage.REGISTERED_SUCCESS, bean);
            }

            return getsBaseBean(RequestCode.ERROR_ACCOUNT_REPEAT, RequestMassage.ACCOUNT_REPEAT, null);
        }


        return getsBaseBean(RequestCode.ERROR_REGISTERED_FAILED, RequestMassage.REGISTERED_FAILED, null);
    }


    /**
     * 创建订单
     * @param req
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("s1/customer/createOrder")
    public String createOrder(@RequestHeader Map<String, String> header, @RequestBody AddOrderReq req) throws JsonProcessingException {

        /**
         * 下单测试数据
         */
     //   "goodGroup":"[{\"goodId\":40,\"categoryId\":21, \"num\":1,\"normsList\": [{ \"normsId\":35,\"attributeId\": 124},{\"normsId\":34,\"attributeId\": 119}]},{\"goodId\":42,\"categoryId\":21,\"num\":1,\"normsList\": [{ \"normsId\":35, \"attributeId\":122},{\"normsId\":34,\"attributeId\":116}]}]"


        String token = processCustomerToken(header);
        if (!token.equals(ConfigCode.TOKEN_OK)) {
            return token;
        }
        int uid = Integer.valueOf(getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(0));
        CustomerInfoReq bean=customerMapper.selectUidAccount(uid);
        req.setBusinessLicense(bean.getBusinessLicense());
        req.setCustomerId(uid);
        req.setCustomerAccount(bean.getPhone());
        req.setOrderState(0);
        req.setOrderDate(toDate(req.getOrderTime()));
        int code=customerMapper.createOrder(req);
        if (!isEmpty(req.getGoodGroup())){
            List<OrderIdResultBean> listOrderGoods= JSONObject.parseObject(req.getGoodGroup(), new TypeReference<List<OrderIdResultBean>>(){});

            for (OrderIdResultBean goods :  listOrderGoods){
                GoodsListReq goodsReq=new GoodsListReq();
                goodsReq.setId(goods.getGoodId());
                goodsReq.setCategoryId(goods.getCategoryId());
                GoodsResultBean goodsResultBean=customerMapper.getGoodInfo(goodsReq);
                OrderGoodsReq orderGoodsReq=new OrderGoodsReq();
                orderGoodsReq.setCategoryId(goods.getCategoryId());
                orderGoodsReq.setGoodsAttribute(JSONObject.toJSONString(goods.getNormsList()));
                orderGoodsReq.setGoodsId(goodsResultBean.getId());
                orderGoodsReq.setGoodsName(goodsResultBean.getGoodsName());
                orderGoodsReq.setGoodsNum(goods.getNum());
                orderGoodsReq.setGoodsPrice(goodsResultBean.getGoodsPrice());
                orderGoodsReq.setOrderTime(req.getOrderTime());
                orderGoodsReq.setOrderAccount(req.getCustomerAccount());
                int goodsCode=   customerMapper.createOrderGoods(orderGoodsReq);
            }

        }

        return returnResultInfo(code==1?RequestCode.SUCCESS_CODE : RequestCode.ERROR_UPDATE_FAILED);

    }


    /**
     * 用户登录
     * @param req
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("s1/customer/login")
    public String customerLogin(@RequestHeader Map<String, String> header, @RequestBody RegisteredReq req) throws JsonProcessingException {
        RegisteredReq registeredBean = customerMapper.selectAccount(req);
        if (registeredBean != null) {
            boolean isLogin = MdProcess.verify(req.getCustomerPwd(), registeredBean.getCustomerPwd());
            if (isLogin){
                String token=tokenService.getCustomerToken(registeredBean);
                registeredBean.setToken(token);
                LoginResultBean  resultBean=new LoginResultBean();
                resultBean.setCustomerAccount(registeredBean.getCustomerAccount());
                resultBean.setToken(token);
                customerMapper.updateToken(registeredBean);
               return returnResultInfo(RequestCode.SUCCESS_CODE,resultBean);
            }

            return returnResultInfo( RequestCode.ERROR_PASSWORD);
        }
        return returnResultInfo(RequestCode.ERROR_SELECT_FAILED);

    }

    @PostMapping("s1/customer/selectCategory")
    @JsonProperty(value = "DOI")
    public String selectCategory(@RequestHeader Map<String, String> header,@RequestBody GoodsListReq req) throws JsonProcessingException {
        if (req == null) {
            return returnResultInfo(RequestCode.ERROR_UPLOAD_CODE);
        }
        if (isEmpty(req.getBusinessLicense())){
            String token = processToken(header);
            if (!token.equals(ConfigCode.TOKEN_OK)) {
                return token;
            }

            if (req == null) {
                return returnResultInfo(RequestCode.ERROR_UPLOAD_CODE);
            }
            UserBean userBean = baseMapper.selectUserById(getUid(header));
            req.setBusinessLicense(userBean.getBusinessLicense());
        }

        List<OrderCategoryGoodsBean> list = customerMapper.selectGoodsCategory(req.getBusinessLicense());
        if (list!=null){
            for (OrderCategoryGoodsBean goodsBean:list){
                req.setCategoryId(goodsBean.getId());
                List<GoodsResultBean> listGoods= customerMapper.getGoodsList(req);
                for (GoodsResultBean bean:listGoods){

                    if (bean.getNormsList()!=null&&!bean.getNormsList().isEmpty()){
                        List<NormsBean> listNorms=new ArrayList<>();
                        List<NormsIds> listNormsId= JSONObject.parseObject(bean.getNormsList(), new TypeReference<List<NormsIds> >(){});
                        if (listNormsId!=null&& listNormsId.size()>0){
                            for(int i=0;i<listNormsId.size();i++){
                                NormsIds ids=listNormsId.get(i);
                                NormsReq normsReq=new NormsReq();
                                normsReq.setId(ids.getNormsId());
                                NormsBean normsBean=customerMapper.getOrderNorms(normsReq);
                                GoodsNormsAttributeReq attributeReq=new GoodsNormsAttributeReq();
                                attributeReq.setNormsId(ids.getNormsId());
                                attributeReq.setIds(ids.getList());
                                List<NormsAttributeInsertReq> listAttribute=customerMapper.getGoodNormsAttributeList(attributeReq);
                                if (listAttribute!=null&& listAttribute.size()>0){
                                    normsBean.setListAttribute(listAttribute);
                                }
                                if (normsBean!=null){
                                    listNorms.add(normsBean);
                                }

                            }
                        }
                        bean.setListNorms(listNorms);
                    }
                }
                goodsBean.setGoodsList(listGoods);
            }
        }


        return returnResultInfo(RequestCode.SUCCESS_CODE, list);
    }


    /**
     * 查询用户信息
     * @param header
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("s1/customer/selectCustomerInfo")
    @JsonProperty(value = "DOI")
    public String selectCustomerInfo(@RequestHeader Map<String, String> header) throws JsonProcessingException {

        String token = processCustomerToken(header);
        if (!token.equals(ConfigCode.TOKEN_OK)) {
            return token;
        }

        int uid = Integer.valueOf(getTokenCode(header.get(ConfigCode.HEADER_TOKEN_KEY)).get(0));
        CustomerInfoReq bean=customerMapper.selectUidAccount(uid);
        return returnResultInfo(RequestCode.SUCCESS_CODE,bean);

    }





    //https://www.cnblogs.com/javastack/p/13891251.html 分页
}
